<template>
  <div class="health-data-container">
    <div class="page-header">
      <h1>健康数据管理</h1>
      <el-button type="primary" @click="openAddDialog">
        <el-icon><Plus /></el-icon> 添加健康数据
      </el-button>
    </div>
    
    <el-card v-loading="loading">
      <template #header>
        <div class="card-header">
          <el-input
            v-model="searchQuery"
            placeholder="搜索数据类型"
            clearable
            style="width: 200px"
          />
          <el-select v-model="selectedDataType" placeholder="按类型筛选" clearable>
            <el-option
              v-for="type in dataTypes"
              :key="type"
              :label="type"
              :value="type"
            />
          </el-select>
        </div>
      </template>
      
      <div v-if="filteredData.length === 0" class="no-data">
        <el-empty description="暂无健康数据" />
      </div>
      
      <el-table v-else :data="filteredData" style="width: 100%">
        <el-table-column prop="data_type" label="数据类型" sortable />
        <el-table-column label="数值" sortable>
          <template #default="scope">
            {{ scope.row.value }} {{ scope.row.unit }}
          </template>
        </el-table-column>
        <el-table-column prop="notes" label="备注" show-overflow-tooltip />
        <el-table-column label="记录时间" sortable>
          <template #default="scope">
            {{ formatDate(scope.row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150">
          <template #default="scope">
            <el-button type="primary" size="small" @click="openEditDialog(scope.row)">
              编辑
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(scope.row.id)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    
    <!-- 添加/编辑健康数据对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEditing ? '编辑健康数据' : '添加健康数据'"
      width="500px"
    >
      <el-form :model="formData" :rules="rules" ref="dataForm" label-width="100px">
        <el-form-item label="数据类型" prop="data_type">
          <el-select
            v-model="formData.data_type"
            placeholder="选择数据类型"
            filterable
            allow-create
            default-first-option
            style="width: 100%"
          >
            <el-option
              v-for="type in commonDataTypes"
              :key="type.value"
              :label="type.label"
              :value="type.value"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="数值" prop="value">
          <el-input-number v-model="formData.value" :precision="2" :step="0.1" style="width: 100%" />
        </el-form-item>
        
        <el-form-item label="单位" prop="unit">
          <el-input v-model="formData.unit" placeholder="如: kg, mmHg, mg/dL等" />
        </el-form-item>
        
        <el-form-item label="备注" prop="notes">
          <el-input
            v-model="formData.notes"
            type="textarea"
            placeholder="添加备注信息"
            :rows="3"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm" :loading="submitting">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted } from 'vue'
import { useStore } from 'vuex'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'

export default {
  name: 'HealthData',
  components: {
    Plus
  },
  setup() {
    const store = useStore()
    const dataForm = ref(null)
    
    // 数据
    const healthData = ref([])
    const loading = ref(false)
    const submitting = ref(false)
    
    // 搜索和筛选
    const searchQuery = ref('')
    const selectedDataType = ref('')
    
    // 对话框控制
    const dialogVisible = ref(false)
    const isEditing = ref(false)
    const currentId = ref(null)
    
    // 表单数据
    const formData = reactive({
      data_type: '',
      value: '',
      unit: '',
      notes: ''
    })
    
    // 表单验证规则
    const rules = {
      data_type: [
        { required: true, message: '请选择或输入数据类型', trigger: 'blur' }
      ],
      value: [
        { required: true, message: '请输入数值', trigger: 'blur' }
      ],
      unit: [
        { required: true, message: '请输入单位', trigger: 'blur' }
      ]
    }
    
    // 常见健康数据类型
    const commonDataTypes = [
      { label: '体重', value: '体重' },
      { label: '身高', value: '身高' },
      { label: '体温', value: '体温' },
      { label: '血压(收缩压)', value: '血压(收缩压)' },
      { label: '血压(舒张压)', value: '血压(舒张压)' },
      { label: '心率', value: '心率' },
      { label: '血氧', value: '血氧' },
      { label: '血糖', value: '血糖' },
      { label: '总胆固醇', value: '总胆固醇' },
      { label: '步数', value: '步数' }
    ]
    
    // 计算所有数据类型
    const dataTypes = computed(() => {
      const types = new Set(healthData.value.map(item => item.data_type))
      return Array.from(types)
    })
    
    // 根据搜索和筛选条件过滤数据
    const filteredData = computed(() => {
      let result = healthData.value
      
      if (searchQuery.value) {
        const query = searchQuery.value.toLowerCase()
        result = result.filter(item => 
          item.data_type.toLowerCase().includes(query) || 
          (item.notes && item.notes.toLowerCase().includes(query))
        )
      }
      
      if (selectedDataType.value) {
        result = result.filter(item => item.data_type === selectedDataType.value)
      }
      
      return result
    })
    
    // 格式化日期
    const formatDate = (dateString) => {
      const date = new Date(dateString)
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      })
    }
    
    // 获取所有健康数据
    const fetchHealthData = async () => {
      loading.value = true
      try {
        const data = await store.dispatch('healthData/fetchHealthData')
        healthData.value = data
      } catch (error) {
        ElMessage.error('获取健康数据失败')
        console.error(error)
      } finally {
        loading.value = false
      }
    }
    
    // 打开添加对话框
    const openAddDialog = () => {
      isEditing.value = false
      currentId.value = null
      
      // 重置表单
      Object.keys(formData).forEach(key => {
        formData[key] = ''
      })
      
      dialogVisible.value = true
    }
    
    // 打开编辑对话框
    const openEditDialog = (row) => {
      isEditing.value = true
      currentId.value = row.id
      
      // 填充表单数据
      Object.keys(formData).forEach(key => {
        formData[key] = row[key]
      })
      
      dialogVisible.value = true
    }
    
    // 提交表单
    const submitForm = async () => {
      if (!dataForm.value) return
      
      await dataForm.value.validate(async (valid) => {
        if (valid) {
          submitting.value = true
          
          try {
            if (isEditing.value) {
              // 更新
              await store.dispatch('healthData/updateHealthData', {
                id: currentId.value,
                healthData: formData
              })
              ElMessage.success('健康数据更新成功')
            } else {
              // 添加
              await store.dispatch('healthData/addHealthData', formData)
              ElMessage.success('健康数据添加成功')
            }
            
            // 关闭对话框并刷新数据
            dialogVisible.value = false
            await fetchHealthData()
          } catch (error) {
            ElMessage.error(isEditing.value ? '更新健康数据失败' : '添加健康数据失败')
            console.error(error)
          } finally {
            submitting.value = false
          }
        }
      })
    }
    
    // 删除健康数据
    const handleDelete = (id) => {
      ElMessageBox.confirm('确定要删除这条健康数据吗？此操作不可逆', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          loading.value = true
          try {
            await store.dispatch('healthData/deleteHealthData', id)
            ElMessage.success('健康数据删除成功')
            await fetchHealthData()
          } catch (error) {
            ElMessage.error('删除健康数据失败')
            console.error(error)
          } finally {
            loading.value = false
          }
        })
        .catch(() => {
          // 取消删除
        })
    }
    
    // 页面加载时获取数据
    onMounted(() => {
      fetchHealthData()
    })
    
    return {
      healthData,
      loading,
      submitting,
      searchQuery,
      selectedDataType,
      dialogVisible,
      isEditing,
      formData,
      rules,
      dataForm,
      commonDataTypes,
      dataTypes,
      filteredData,
      formatDate,
      openAddDialog,
      openEditDialog,
      submitForm,
      handleDelete
    }
  }
}
</script>

<style scoped>
.health-data-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h1 {
  margin: 0;
  color: #409EFF;
}

.card-header {
  display: flex;
  gap: 15px;
}

.no-data {
  padding: 40px 0;
}
</style> 